<template>
  <div class="Jurisdiction common">
    <div class="Jurisdiction-content">
      <div class="block mt15">
        <el-tree
          key="1"
          :data="data2"
          node-key="id"
          default-expand-all
          auto-expand-parent
          :expand-on-click-node="false"
          v-loading="loading"
          @node-drag-start="handleDragStart"
          @node-drag-enter="handleDragEnter"
          @node-drag-leave="handleDragLeave"
          @node-drag-over="handleDragOver"
          @node-drag-end="handleDragEnd"
          :draggable = "userInfo&&userInfo.items[0].role.indexOf('管理员')>=0"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag">
          <div class="custom-tree-node" slot-scope="{ node, data }">
              <div class="block dis-flex">
                <span class="w300p" v-if="!data.edit">
                  {{ data.label }}
                  <el-tooltip v-for="tag in arrSlice(node.data.existed_user, 0 ,8)"
                  :key="tag.user_id" class="item" effect="dark" :content="tag.title_name" placement="top-end">
                    <el-button size="mini" type="success" round plain>{{tag.user_cname}}</el-button>
                  </el-tooltip>
                  <el-button type="success" size="mini" icon="el-icon-search" circle @click="handleGetBlockUser(node.data.id)"></el-button>
                </span>
                <el-input ref="editInput" :autofocus="data.edit" @blur="() => emitInput(node, data)"  size="mini" v-else v-model="data.label" placeholder="您要创建的组织名字"></el-input>
                <span>
                  <el-button
                    v-if="(userInfo.items[0].role.indexOf('管理员') >= 0 || userInfo.items[0].role.indexOf('商务助理') >= 0)"
                    type="primary"
                    size="mini"
                    @click="() => appendSiblings(node,data)" plain class="ml15">
                      新建同级
                  </el-button>
                  <el-button
                    v-show="(userInfo.items[0].role.indexOf('管理员') >= 0 || userInfo.items[0].role.indexOf('商务助理') >= 0)&&data.label!==''&&node.data.parent_id"
                    type="primary"
                    size="mini"
                    @click="() => append(node,data)" plain class="ml15">
                      新建下级
                  </el-button>
                  <el-button
                    type="primary"
                    size="mini"
                    v-show="(userInfo.items[0].role.indexOf('管理员') >= 0 || userInfo.items[0].role.indexOf('商务助理') >= 0)&&data.label!==''"
                    @click="() => emitInputEdit(node, data)" plain class="ml15">编辑</el-button>
                  <el-button
                    v-if="(userInfo.items[0].role.indexOf('管理员') >= 0 || userInfo.items[0].role.indexOf('商务助理') >= 0)&&(!node.data.children||node.data.children.length==0&&node.data.parent_id)"
                    type="danger"
                    size="mini"
                    @click="() => remove(node, data)" plain class="ml15">
                      删除
                  </el-button>
                </span>
              </div>
          </div>
        </el-tree>
      </div>
      <!-- 新增弹窗或者编辑弹窗 -->
      <el-dialog :modal-append-to-body="false"
        :top="userAgent ? '60px' : '15vh'"
        title="修改组织名称"
        :visible.sync="dialogVisible"
        width="40%"
        center>
        <el-form ref="form" :model="form" label-width="100px" class="w80p block-center">
          <el-form-item label="修改前名称：">
            <el-input :disabled="true" v-model="form.before_name"></el-input>
          </el-form-item>
          <el-form-item label="修改后名称：">
            <el-input v-model="form.after_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editBlockName">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 查看单个区块详细名单 -->
      <el-dialog :modal-append-to-body="false"
        :top="userAgent ? '60px' : '15vh'"
        :title="tempBlockDetail.title"
        :visible.sync="dialogVisible1"
        width="40%"
        center>
        <el-table :height="userAgent ? '' : '550'" :data="tempBlockDetail.tabList" class="w90p block-center">
          <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
          <el-table-column property="user_cname" label="姓名" align="center"></el-table-column>
          <el-table-column property="user_phone" label="手机" align="center"></el-table-column>
          <el-table-column property="user_wx" label="微信" align="center"></el-table-column>
          <el-table-column property="title_name" label="岗位" align="center"></el-table-column>
        </el-table>
        <el-pagination
          class="block-center tac mt10"
          small
          layout="total, prev, pager, next"
          :page-size="tempBlockDetail.per_page"
          :total="tempBlockDetail.total"
          @current-change="pageChange">
        </el-pagination>
      </el-dialog>

      <el-dialog :modal-append-to-body="false" :top="userAgent ? '60px' : '15vh'" title="部门人员" :visible.sync="dialogTableVisible" @close="closeDialog">
      <el-table :data="logData">
        <el-table-column prop="user_cname" label="姓名" align="center"></el-table-column>
        <el-table-column prop="user_phone" label="手机" align="center"></el-table-column>
        <el-table-column prop="user_wx" label="微信" align="center"></el-table-column>
        <el-table-column prop="title_name" label="岗位" align="center"></el-table-column>
      </el-table>
      <div class="block tac mt20">
        <el-pagination
          small
          layout="prev, pager, next"
          :total="dialogPageTotal"
          :current-page="dialogPage"
          @current-change="dialogPageChange">
        </el-pagination>
      </div>
    </el-dialog>
    </div>
  </div>
</template>
<script>
import { resolve } from 'q';
let id = 100;
export default {
  name: "groupmanage",
  data() {
    return {
      loading:false,
      block_id: 0, // 区块树的block_id
      inputVal: '',// 要创建的部门名称
      department_id: 1,// 部门ID
      data2: [],
      dialogVisible: false,
      dialogVisible1: false,//详细单个区块名单
      dialogTableVisible: false,
      allLogData: [],
      logData: [],
      dialogPage: 1,
      dialogPageTotal: 0,
      block_user_id: 0,
      tempBlockDetail:{
        title: '',
        tabList: [],
        tempTotalList: [],
        total: 0,
        page:1,
        per_page:7
      },
      createBlockForm:{
        parent_id: 0,
        name:''
      },
      form: {
        before_name:'',
        after_name:'',
        id: ''
      },
      middleData:{
        id: ''
      },
      allBlocks: [],
      secondGroupList: [], // 存储不能拖拽的部门,总部和二级部门
      dargLocation:{
        before: '前面',
        after:'后面',
        inner:'里面'
      }

    }
  },
  methods: {
    pageChange(r){
      let start = (r-1)* this.tempBlockDetail.per_page;
      let end = r * this.tempBlockDetail.per_page;
      this.tempBlockDetail.page = r;
      this.tempBlockDetail.tabList = this.tempBlockDetail.tempTotalList.slice(start,end)
    },
    // 获取区块树
    arrSlice(arr, start, end){
      if(!arr) return arr;
      if(arr&&arr.length===0) return arr;
      return arr.slice(start, end)
    },
    getBlockTree() {
      this.loading = true;
      this.$api.getBlockTree({
        params: {
          block_id: this.block_id
        }
      }).then(res => {
          this.loading = false;
          this.$notify({
            title: "提示",
            message: "获取组织架构成功",
            type: "success"
          });
          this.data2 = [];
          this.data2.push(res)
      })
      .catch(() => {})
    },
    // 获取所有区块
    async getAllBlocks(){
      let allBlocks = [];
      let promise = new Promise((resolve, reject) =>{
        this.$api.getAllBlocks().then(res => {
          allBlocks = res.items;
          res.items.map(o =>{
            if(!o.parent_id){
              this.block_id = o.id;
              return;
            }
          });
          this.getBlockTree();
          resolve(this.block_id);
        })
        .catch(() => {})
      });
      let base_id = await promise;
      // 返回总部和总部第二级不可拖拽的数据
      this.secondGroupList = allBlocks.filter(ele => {
        return ele.parent_id === base_id || ele.id == base_id;
      })
    },
    //创建某个区块
    createBlockItem(){
      this.$api.createBlockItem({
        parent_id: this.createBlockForm.parent_id,
        name: this.createBlockForm.name,
        department_id:this.department_id
      }).then(res => {
        if(res.err_no===0){
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success"
          });
          this.getBlockTree()
        }

      })
      .catch(() => {})
    },
    // 编辑区块名字
    editBlockName(){
      if(!this.form.after_name){
        this.$notify({
          title: "提示",
          message: "请输入您要修改的名称哦",
          type: "warning"
        });
        return false;
      }
      this.$api.editBlockItem({
        id: this.form.id,
        name: this.form.after_name
      }).then(res=>{
        if(res.err_no===0){
          this.$notify({
              title: "提示",
              message: "修改区块成功",
              type: "success"
          });
          this.dialogVisible = false;
          this.getBlockTree();
        }
      })
      .catch(()=>{})
    },
    // 删除区块
    deleteBlockItem(){
      this.$api.deleteBlockItem({
        data:{
          id: this.middleData.id}
        }).then(res=>{
          this.$notify({
              title: "提示",
              message: "删除区块成功",
              type: "success"
          });
          this.getBlockTree()
      })
      .catch(()=>{})
    },
    append(node,data) {
      const newChild = { label: '', children: [] ,edit: true};
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      // 清除多余的input框
      if(this.$refs.editInput&&this.$refs.editInput.value===''){
        this.$refs.editInput.focus();
        this.$refs.editInput.blur();
      }
      data.children.push(newChild);
    },
    appendSiblings(node,data) {
      const parent = node.parent;
      const newChild = { label: '', children: [],edit:true};
      // 清除多余的input框
      if(this.$refs.editInput&&this.$refs.editInput.value===''){
        this.$refs.editInput.focus();
        this.$refs.editInput.blur();
      }
      if(parent.data instanceof Array){
        parent.data.push(newChild )
      }else{
        parent.data.children.push(newChild)
      }
    },
    remove(node, data) {
      this.middleData.id = data.id;
      this.$confirm('此操作将永久删除该组织, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteBlockItem();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    emitInput(node, data){
      if(data.label){
        data.edit = false;
        this.createBlockForm = {
          parent_id: node.parent.data.id, // 父节点的id
          name: data.label
        }
        this.createBlockItem()
      }else{
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      }
    },
    emitInputEdit(node, data){
      this.dialogVisible = true;
      this.form = {
        before_name : data.label,
        after_name: '',
        id: data.id
      }
    },
    seeMoreData(data){
      this.tempBlockDetail = {
        title: `${data.label}人员名单`,
        tempTotalList: data.existed_user,
        tabList: data.existed_user.slice(0,this.tempBlockDetail.per_page),
        total: data.existed_user.length,
        page:1,
        per_page:7
      }
      this.dialogVisible1 = true
    },
    removeShowBlock(node, data){
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
    handleDragStart(node, ev) {},
    handleDragEnter(draggingNode, dropNode, ev) {},
    handleDragLeave(draggingNode, dropNode, ev) {},
    handleDragOver(draggingNode, dropNode, ev) {},
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      if(dropType==="none") return;
      let p = {
        id: String(draggingNode.data.id),
        parent_id: String(dropNode.data.parent_id)
      }
      if(dropType==="inner"){
        p.parent_id = String(dropNode.data.id)
      }
      this.$confirm(`您确定要把【${draggingNode.data.label}】移动到【${dropNode.data.label}】${this.dargLocation[dropType]}吗`, '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        .then(() => {
          this.$api.editBlockPosiyion(p)
          .then(res=>{
            this.$notify({
              title: "提示",
              message: "移动成功",
              type: "success"
            });
            this.getBlockTree();
          })
        })
        .catch(() => {
          this.$notify({
            title: "提示",
            message: "放弃移动成功",
            type: "success"
          });
          this.getBlockTree();
        });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {},
    allowDrop(draggingNode, dropNode, type) {
      return this.secondGroupList.every(ele=>{
        return  dropNode.data.id !== ele.id;
      })
    },
    allowDrag(draggingNode) {
      return this.secondGroupList.every(ele=>{
        return  draggingNode.data.id !== ele.id;
      })
    },
    handleGetBlockUser(id) {
      this.block_user_id = id
      this.$api.getBlockUser({
        params: {
          block_id: id
        }
      }).then((res) => {
        this.allLogData = res
        this.logData = this.arrSlice(res, 0, 8)
        this.dialogPageTotal = res.length
        this.dialogTableVisible = true
      })
    },
    dialogPageChange(p){
      this.dialogPage = p;
      let start = (p - 1) * 8;
      let end = p * 8
      this.logData = this.arrSlice(this.allLogData, start, end)
    },
    closeDialog() {
      this.dialogPage = 1
    },
  },
  created() {
    this.getAllBlocks();
  }
};
</script>
<style lang="stylus" scoped>
.custom-tree-node
  width 100%
.dis-flex
  width 100%
  flex 1
  display flex
  align-items center
  justify-content space-between
  font-size 14px
  padding-right 8px
.w300p
  width 300px
.block-center
  margin 0 auto
.w90p
  width 90%
.mt10
  margin-top 10px
</style>
